import {
    createRouter,
    createWebHashHistory,
} from "vue-router";
import RouterConfig from "../router/config"
import store from "@/store";

import LoginView from "../views/login/LoginView.vue"
import IndexView from "../views/index/IndexView.vue"


const routes = [
    {
        path: "/login",
        name: "login",
        component: LoginView,
    }, {
        path: "/",
        redirect: "/home"
    }, {
        path: "/index",
        name: "index",
        component: IndexView
    },{
        path:"/:pathMatch(.*)*",
        name:"Notfound",
        component:()=>import("../views/NotFound.vue")
    }
];

const router = createRouter({
    //createWebHistory路由模式路径不带#号(生产环境下不能直接访问项目，需要nginx转发)
    //createWebHashHistory路由模式路径带#号
    history: createWebHashHistory(),
    routes,
})

router.beforeEach((to, from, next) => {
    if (to.name === "login") {
        next()
    } else {
        // 如果已经登录 next()
        // 未登录 重定向到login
        if (!localStorage.getItem("token")) {
            next({
                path: "/login"
            })
        } else {
            if(!store.state.isGetterRouter){
                ConfigRouter()
                next({
                    path:to.fullPath
                })
            }else{
                next()
            }
        }
    }
})

const ConfigRouter = () => {
    RouterConfig.forEach(item => {
        // router.addRoute添加子路由
        router.addRoute("index", item)
    })
    store.commit("changeGetterRouter",true)
}

export default router;  //导出
